package com.jzoffer2;

import java.util.Arrays;

/**
 * TODO
 *
 * @author lefly
 * @version 1.0
 * @classname No29
 * @description
 * @date 2021/2/1 下午1:09
 */
public class No29 {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        int[] res= spiralOrder(matrix);
        System.out.println(Arrays.toString(res));
    }

    public static int[] spiralOrder(int[][] matrix) {
        if(matrix == null || matrix.length < 1 || matrix[0].length < 1){
            return new int[0];
        }
        int rows = matrix.length,cols = matrix[0].length;
        int[] res = new int[rows * cols];
        int k = 0;
        int r1 = 0,r2 = rows - 1,c1 = 0,c2 = cols - 1;
        while (r1 <= r2 && c1 <= c2 ){
            for (int i = c1; i <= c2 ; i++) {
                res[k++] = matrix[r1][i];
            }
            for (int i = r1 + 1; i <= r2 ; i++) {
                res[k++] = matrix[i][c2];
            }
            if(r1 != r2){
                for (int i = c2 - 1; i >= c1 ; i--) {
                    res[k++] = matrix[r2][i];
                }
            }
            if(c1 != c2){
                for (int i = r2 - 1; i > r1 ; i--) {
                    res[k++] = matrix[i][c1];
                }
            }
            c1++;
            c2--;
            r1++;
            r2--;
        }
        return res;

    }


}
